import React, { useEffect, useState } from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useAuthStore } from '../services/store';
import { Loading } from './ui';

interface AuthGuardProps {
  children: React.ReactNode;
  requiredRole?: 'admin' | 'editor' | 'viewer';
}

const AuthGuard: React.FC<AuthGuardProps> = ({ 
  children, 
  requiredRole = 'viewer' 
}) => {
  const location = useLocation();
  const { user, isAuthenticated, loading, checkAuth } = useAuthStore();
  const [initialCheck, setInitialCheck] = useState(false);

  useEffect(() => {
    // 如果已经认证或者没有token，直接标记检查完成
    const token = localStorage.getItem('auth_token');
    if (isAuthenticated || !token) {
      setInitialCheck(true);
    } else if (token && !isAuthenticated && !initialCheck) {
      // 只有在有token但未认证且未进行初始检查时才检查
      setInitialCheck(true);
      checkAuth();
    }
  }, [isAuthenticated, checkAuth, initialCheck]);

  // 正在加载认证状态或初始检查未完成
  if (loading || !initialCheck) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Loading size="large" text="验证登录状态..." />
      </div>
    );
  }

  // 未登录，重定向到登录页
  if (!isAuthenticated || !user) {
    return (
      <Navigate 
        to="/login" 
        state={{ from: location.pathname }} 
        replace 
      />
    );
  }

  // 检查角色权限
  const roleHierarchy = {
    viewer: 1,
    editor: 2,
    admin: 3
  };

  const userRoleLevel = roleHierarchy[user.role as keyof typeof roleHierarchy] || 0;
  const requiredRoleLevel = roleHierarchy[requiredRole] || 0;

  // 权限不足
  if (userRoleLevel < requiredRoleLevel) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-4xl font-bold text-gray-900 mb-4">403</h1>
          <p className="text-gray-600 mb-4">抱歉，您没有访问此页面的权限</p>
          <button 
            onClick={() => window.history.back()}
            className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
          >
            返回上一页
          </button>
        </div>
      </div>
    );
  }

  return <>{children}</>;
};

export default AuthGuard;